<template>
  <div class="subAccount">
    <!-- 角色管理页面 -->
    <!-- 新增按钮 -->
    <el-button type="primary" style="padding: 5px 20px" @click="handleAddUser">新建角色</el-button>
    <!-- 用户列表 -->
    <div class="tableData">
      <el-table :data="tableData" style="width: 100%;margin-bottom: 40px">
        <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
        <el-table-column align="center" prop="sv_d_role_name" label="角色"></el-table-column>
        <el-table-column
          min-width="200"
          :show-overflow-tooltip="true"
          align="center"
          prop="sv_d_role_remark"
          label="角色描述"
        ></el-table-column>
        <el-table-column
          min-width="160"
          align="center"
          prop="sv_creation_date"
          :formatter="dateFormat"
          label="创建时间"
        ></el-table-column>
        <!-- :formatter="dateFormat" -->
        <el-table-column align="center" label="启用状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.sv_enabled" @change="handleToggle(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column min-width="190" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              style="padding: 3px 8px"
              @click="handleJurisdiction(scope.row)"
            >权限分配</el-button>
            <el-button
              type="success"
              style="padding: 3px 8px"
              @click="handleChangeUser(scope.row)"
            >修改</el-button>
            <el-button type="danger" style="padding: 3px 8px" @click="handleDele(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 这个是分页器 -->
    <Pagination
      :total="total"
      :pageIndex="pageIndex"
      :pageSize="pageSize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    ></Pagination>
    <!-- 弹出框 -->
    <!-- 新增角色 -->
    <div class="roleDetail" v-show="visible1">
      <div class="content" style="width: 350px">
        <h3 class="title" style="font-size: 16px;margin-bottom: 20px">新增角色</h3>
        <div class="close" @click="visible = false">
          <i class="fa fa-times" aria-hidden="true"></i>
        </div>
        <el-col :offset="1">
          <el-form label-width="80px" :model="formLabelAlign">
            <el-form-item style="width: 60%" size="mini" label="角色名称">
              <el-input v-model="formLabelAlign.sv_d_role_name"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="角色描述">
              <el-input v-model="formLabelAlign.sv_d_role_remark"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="状态">
              <el-switch @change="handleToggle" v-model="formLabelAlign.sv_enabled"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="addUser">确定</el-button>
              <el-button size="mini" @click="visible1 = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </div>
    </div>
    <!-- 修改角色 -->
    <div class="roleDetail" v-show="visible2">
      <div class="content" style="width: 350px">
        <h3 class="title" style="font-size: 16px;margin-bottom: 20px">修改角色</h3>
        <div class="close" @click="visible = false">
          <i class="fa fa-times" aria-hidden="true"></i>
        </div>
        <el-col :offset="1">
          <el-form label-width="80px" :model="formLabelAlign">
            <el-form-item style="width: 60%" size="mini" label="角色名称">
              <el-input v-model="formLabelAlign.sv_d_role_name"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="角色描述">
              <el-input v-model="formLabelAlign.sv_d_role_remark"></el-input>
            </el-form-item>
            <el-form-item v-show="isShow" style="width: 60%" size="mini" label="角色ID">
              <el-input v-model="formLabelAlign.sv_d_role_id"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="状态">
              <el-switch @change="handleToggle" v-model="formLabelAlign.sv_enabled"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="changeUser">确定</el-button>
              <el-button size="mini" @click="visible2 = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </div>
    </div>
    <!-- 权限管理 -->
    <div class="roleDetail" v-show="authority">
      <div class="content" style="width: 400px">
        <h3 class="title" style="font-size: 16px;margin-bottom: 20px">权限分配</h3>
        <div class="close" @click="authority = false">
          <i class="fa fa-times" aria-hidden="true"></i>
        </div>
        <el-tree
          :data="roleConfigData"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-checked-keys="checkedKeys"
          highlight-current
          :props="defaultProps"
          style="height: 300px;overflow: scroll;overflow-x: hidden;"
        ></el-tree>
        <div class="btnRole" style="text-align: center;margin-top: 40px">
          <el-button type="primary" size="mini" @click="getCheckedNodes">确定</el-button>
          <el-button size="mini" @click="authority = false">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex"; //注册state
import Pagination from "@/components/Pagination";
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 这个是弹出框里的数据
      formLabelAlign: {
        sv_d_role_name: "",
        sv_d_role_id: "",
        sv_d_role_remark: "",
        sv_enabled: true
      },
      // 修改角色数据
      visible1: false,
      visible2: false,
      isShow: false,
      // 修改权限数据
      authority: false,
      // 修改权限需要的数据
      distributor_id: "",
      role_id: "",
      // 发送的配置数据
      roleConfig: [],
      // 默认勾选的key
      checkedKeys: [27],
      // 树状数据关联
      roleConfigData: [],
      defaultProps: {
        children: "children",
        label: "page_name"
      },
      // 分页器的数据
      total: 0, // 总条数
      pageIndex: 1, // 当前页
      pageSize: 10, // 每页数量
      // 令牌
      myToken: ""
    };
  },
  components: {
    Pagination
  },
  computed: {
    // 引入权限数据
    ...mapState(["slideData"]),
    ...mapState(["userId"])
  },
  methods: {
    // 获取角色列表
    getOrderData() {
      this.$api
        .getRoleList(this.pageIndex, this.pageSize, this.myToken)
        .then(res => {
          const { dataList, total } = res;
          this.total = total;
          if (dataList == null) {
            this.tableData = null;
            return;
          }
          this.tableData = dataList.map(v => {
            return {
              ...v
            };
          });
        });
    },
    //时间格式化
    dateFormat: function(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return this.$moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 分页器的方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getOrderData();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getOrderData();
    },
    // 权限分配
    // 显示权限选择窗口
    handleJurisdiction(val) {
      // console.log(val);
      this.checkedKeys = [27];
      this.authority = true;
      this.distributor_id = val.distributor_id;
      this.role_id = val.sv_d_role_id;
      const configData = JSON.parse(val.sv_d_role_config);
      // console.log(JSON.parse(val.sv_d_role_config));
      for (let j = 0; j < configData.length; j++) {
        if (configData[j] == null) {
          configData.splice(j, 1);
          j--;
        }
      }
      // console.log(configData);
      configData.map(v => {
        return this.checkedKeys.push(v.id);
      });

      this.$refs.tree.setCheckedKeys(this.checkedKeys);
    },
    // 保存权限设置
    getCheckedNodes() {
      this.roleConfig = [];
      this.$refs.tree.getCheckedNodes().map(v => {
        if (v.page_path.indexOf("/") == 0) {
          this.roleConfig.push(v);
        }
        return this.roleConfig;
      });
      // console.log(this.roleConfig);
      this.$api
        .savePermissionSettings(
          this.roleConfig,
          this.distributor_id,
          this.role_id,
          this.myToken
        )
        .then(res => {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.getOrderData();
        });
      this.authority = false;
    },
    // 新增操作
    handleAddUser() {
      this.visible1 = true;
      // 重置表单
      this.formLabelAlign = {
        sv_d_role_name: "",
        sv_d_role_remark: "",
        sv_enabled: true
      };
    },
    // 修改操作
    handleChangeUser(row) {
      this.visible2 = true;
      this.formLabelAlign = row;
    },
    // 新建角色
    addUser() {
      // 正则验证
      // 验证特殊字符
      const patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
      // 角色名称
      if (this.formLabelAlign.sv_d_role_name === "") {
        this.$message.error("请输入角色名称");
        return;
      } else if (this.formLabelAlign.sv_d_role_name.length > 8) {
        this.$message.error("角色名称长度不得超过8字符");
        return;
      } else if (patrn.test(this.formLabelAlign.sv_d_role_name)) {
        this.$message.error("请勿输入特殊字符");
        return;
      }
      // 角色描述
      if (this.formLabelAlign.sv_d_role_remark.length !== 0) {
        if (this.formLabelAlign.sv_d_role_remark === "") {
          this.$message.error("请输入角色描述");
          return;
        } else if (this.formLabelAlign.sv_d_role_remark.length > 20) {
          this.$message.error("角色描述长度不得超过20个字符");
          return;
        } else if (patrn.test(this.formLabelAlign.sv_d_role_remark)) {
          this.$message.error("请勿输入特殊字符");
          return;
        }
      }
      this.$api.creatingRoles(this.formLabelAlign, this.myToken).then(res => {
        if (res.succeed) {
          this.$message({
            type: "success",
            message: "创建成功"
          });
          this.getOrderData();
        }
      });
      this.visible1 = false;
    },
    // 修改角色
    changeUser() {
      // 正则验证
      // 验证特殊字符
      const patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
      // 角色名称
      if (this.formLabelAlign.sv_d_role_name === "") {
        this.$message.error("请输入角色名称");
        return;
      } else if (this.formLabelAlign.sv_d_role_name.length > 8) {
        this.$message.error("角色名称长度不得超过8字符");
        return;
      } else if (patrn.test(this.formLabelAlign.sv_d_role_name)) {
        this.$message.error("请勿输入特殊字符");
        return;
      }
      // 角色描述
      if (this.formLabelAlign.sv_d_role_remark.length !== 0) {
        if (this.formLabelAlign.sv_d_role_remark === "") {
          this.$message.error("请输入角色描述");
          return;
        } else if (this.formLabelAlign.sv_d_role_remark.length > 20) {
          this.$message.error("角色描述长度不得超过20个字符");
          return;
        } else if (patrn.test(this.formLabelAlign.sv_d_role_remark)) {
          this.$message.error("请勿输入特殊字符");
          return;
        }
      }
      this.$api.creatingRoles(this.formLabelAlign, this.myToken).then(res => {
        if (res.succeed) {
          this.$message({
            type: "success",
            message: "修改成功"
          });
          this.getOrderData();
        } else {
          this.$message.error("操作失败");
        }
      });
      this.visible2 = false;
    },
    // 改变账户状态
    handleToggle(val) {
      this.$api
        .changeRolesStatus(val.sv_d_role_id, val.sv_enabled, this.myToken)
        .then(res => {
          this.$message({
            type: "success",
            message: "修改成功"
          });
          this.getOrderData();
        });
    },
    // 删除账户角色
    handleDele(val) {
      this.$confirm(`是否删除角色?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api.deleteRole(val.sv_d_role_id, this.myToken).then(res => {
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.getOrderData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    }
  },
  mounted() {
    // 获取令牌
    this.myToken = sessionStorage.getItem("myToken");
    // 列表初始化
    this.getOrderData();
    // 树状图数据
    this.roleConfigData = this.slideData;
    if (this.userId != 1) {
      for (let i = 0; i < this.roleConfigData.length; i++) {
        if (this.roleConfigData[i].quanxian == "none") {
          this.roleConfigData.splice(i, 1);
          i--;
        }
        for (let j = 0; j < this.roleConfigData[i].children.length; j++) {
          if (this.roleConfigData[i].children[j].quanxian == "none") {
            this.roleConfigData[i].children.splice(j, 1);
            j--;
          }
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
@deep: ~">>>";
.subAccount {
  background-color: #fff;
  padding: 20px;
  height: -webkit-fill-available;
  // 表格
  .tableData {
    margin-top: 20px;
  }
  // 表格表头
  .tableData @{deep} .el-table th {
    background-color: #fafafa;
    color: #252525;
    font-weight: 100;
  }
  // 弹出框的样式
  .roleDetail {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    .content {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      padding: 10px;
      box-sizing: border-box;
      border-radius: 10px;
    }
    .close {
      position: absolute;
      top: 10px;
      right: 10px;
      cursor: pointer;
      color: #666;
      font-size: 20px;
    }
    .content @{deep} .el-tree-node__children .el-checkbox__input {
      visibility: hidden;
    }
  }
  // 修改弹出框中表单内容的宽度
  .roleDetail @{deep} .el-input__inner {
    width: 200px;
  }
}
.subAccount @{deep} .el-table::before {
  height: 0;
}
</style>